import { Component, instantiate, Node, NodePool, Prefab, Rect, UITransform, v3, _decorator } from 'cc';
import { randomSection } from '../../../common/utils';

const { ccclass, property } = _decorator;

@ccclass('GameMap')
export default class GameMap extends Component {
	@property(Node)
	boundaryNd: Node = null!;

	@property(Node)
	decorateNd: Node = null!;

	@property([Prefab])
	decoratePrefabs: Prefab[] = [];

	@property
	decorateCount = 12;

	private _boundary: Rect;
	private _decoratePool: NodePool = new NodePool();

	public getBoundary(): Rect {
		if (!this._boundary) {
			const tranform = this.boundaryNd.getComponent(UITransform);
			this._boundary = new Rect(0, 0, Math.floor(tranform.width), Math.floor(tranform.height));
		}

		return this._boundary;
	}

	public generateMap() {
		for (let i = this.decorateNd.children.length - 1; i >= 0; i--) {
			this._decoratePool.put(this.decorateNd.children[i]);
		}

		for (let i = 0; i < this.decorateCount; i++) {
			const node =
				this._decoratePool.get() ||
				instantiate(this.decoratePrefabs[Math.round(Math.random() * (this.decoratePrefabs.length - 1))]);

			this.decorateNd.addChild(node);

			if (i > 0) {
				const uiTransrom = node.getComponent(UITransform);
				node.setPosition(
					v3(
						randomSection(
							this._boundary.x - this._boundary.width * 0.5 + uiTransrom.width,
							this._boundary.x + this._boundary.width * 0.5 - uiTransrom.width
						),
						randomSection(
							this._boundary.y - this._boundary.height * 0.5 + uiTransrom.height,
							this._boundary.y + this._boundary.height * 0.5 - uiTransrom.height
						),
						0
					)
				);
			} else {
				node.setPosition(v3(50, 50, 0));
			}
		}
	}
}
